<template>
  <div class="order-info-container">
    <div class="page-header">
      <h2>订单信息</h2>
      <p>查看您的订单状态和详细信息</p>
    </div>
    
    <!-- 搜索和筛选栏 -->
    <div class="filter-container">
      <el-input
        v-model="searchQuery"
        placeholder="搜索订单号/商品名称"
        clearable
        class="filter-item"
        @clear="handleFilter"
        @input="handleFilter"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      
      <el-select v-model="statusFilter" placeholder="订单状态" clearable class="filter-item" @change="handleFilter">
        <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
      
          <el-date-picker
        v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        format="YYYY-MM-DD"
        value-format="YYYY-MM-DD"
        class="filter-item date-filter"
        @change="handleFilter"
      />
        </div>
      
    <!-- 订单列表 -->
      <el-table
      v-loading="loading"
      :data="filteredOrders"
      stripe
        border
      style="width: 100%; margin-top: 20px;"
    >
      <el-table-column prop="orderNo" label="订单号" width="180" />
      <el-table-column prop="createTime" label="下单时间" width="180" />
      <el-table-column prop="productName" label="商品名称" min-width="200" show-overflow-tooltip />
      <el-table-column prop="amount" label="金额" width="120">
          <template #default="scope">
          <span class="amount">¥{{ scope.row.amount.toFixed(2) }}</span>
          </template>
        </el-table-column>
      <el-table-column prop="status" label="订单状态" width="120">
          <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
      <el-table-column fixed="right" label="操作" width="160">
          <template #default="scope">
          <el-button type="primary" size="small" @click="viewOrderDetail(scope.row)">查看详情</el-button>
            <el-button
            v-if="scope.row.status === 'pending_payment'" 
              type="success"
              size="small"
            @click="payOrder(scope.row)"
          >
            立即支付
          </el-button>
          </template>
        </el-table-column>
      </el-table>
      
    <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalFilteredOrders"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
      </div>
    
    <!-- 订单详情对话框 -->
    <el-dialog 
      v-model="dialogVisible"
      title="订单详情" 
      width="800px"
      destroy-on-close
    >
      <div class="order-detail" v-if="currentOrder">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号">{{ currentOrder.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="下单时间">{{ currentOrder.createTime }}</el-descriptions-item>
          <el-descriptions-item label="商品名称">{{ currentOrder.productName }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusType(currentOrder.status)">{{ getStatusText(currentOrder.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="订单金额">
            <span class="amount">¥{{ currentOrder.amount.toFixed(2) }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="支付方式">{{ currentOrder.paymentMethod }}</el-descriptions-item>
          <el-descriptions-item label="收货人" :span="2">{{ currentOrder.receiver }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ currentOrder.phone }}</el-descriptions-item>
          <el-descriptions-item label="收货地址" :span="1">{{ currentOrder.address }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="order-items" v-if="currentOrder.items && currentOrder.items.length">
          <h3>订单商品</h3>
          <el-table :data="currentOrder.items" border style="width: 100%; margin-top: 20px;">
            <el-table-column prop="itemName" label="商品名称" min-width="200" />
            <el-table-column prop="specs" label="规格" width="150" />
            <el-table-column prop="price" label="单价" width="120">
              <template #default="scope">
                <span>¥{{ scope.row.price.toFixed(2) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="100" />
            <el-table-column prop="subtotal" label="小计" width="120">
              <template #default="scope">
                <span class="amount">¥{{ scope.row.subtotal.toFixed(2) }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <div class="order-progress" v-if="currentOrder.progress && currentOrder.progress.length">
          <h3>订单进度</h3>
          <el-timeline>
            <el-timeline-item
              v-for="(activity, index) in currentOrder.progress"
              :key="index"
              :timestamp="activity.time"
              :type="index === 0 ? 'primary' : ''"
            >
              {{ activity.content }}
            </el-timeline-item>
          </el-timeline>
        </div>
        
        <div class="remarks" v-if="currentOrder.remarks">
          <h3>订单备注</h3>
          <p>{{ currentOrder.remarks }}</p>
      </div>
      
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="printOrder" :disabled="!currentOrder">打印订单</el-button>
          <el-button 
            v-if="currentOrder.status === 'pending_payment'" 
            type="success" 
            @click="payOrder(currentOrder)"
          >
            立即支付
          </el-button>
          <el-button 
            v-if="['pending_shipment', 'shipped'].includes(currentOrder.status)" 
            type="info" 
            @click="trackOrder(currentOrder)"
          >
            查看物流
          </el-button>
        </div>
      </div>
    </el-dialog>
    
    <!-- 支付对话框 -->
    <el-dialog 
      v-model="paymentDialogVisible"
      title="订单支付"
      width="500px"
      destroy-on-close
    >
      <div class="payment-dialog" v-if="currentOrder">
        <div class="payment-info">
          <p class="payment-title">订单号：{{ currentOrder.orderNo }}</p>
          <p class="payment-amount">支付金额：<span class="amount">¥{{ currentOrder.amount.toFixed(2) }}</span></p>
        </div>
        
        <div class="payment-method">
          <p class="method-title">选择支付方式：</p>
          <el-radio-group v-model="selectedPaymentMethod">
            <el-radio label="alipay">支付宝</el-radio>
            <el-radio label="wechat">微信支付</el-radio>
            <el-radio label="creditcard">银行卡</el-radio>
          </el-radio-group>
        </div>
        
        <div class="payment-tip" v-if="selectedPaymentMethod">
          <el-alert
            title="这是一个演示系统，无需实际支付"
            type="info"
            :closable="false"
            show-icon
          />
        </div>
        
        <div class="dialog-footer">
          <el-button @click="paymentDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmPayment" :disabled="!selectedPaymentMethod">确认支付</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'OrderInfo',
  components: {
    Search
  },
  setup() {
    // 加载状态
    const loading = ref(false)
    
    // 筛选条件
    const searchQuery = ref('')
    const statusFilter = ref('')
    const dateRange = ref([])
    
    // 状态选项
    const statusOptions = [
      { value: 'pending_payment', label: '待支付' },
      { value: 'processing', label: '处理中' },
      { value: 'pending_shipment', label: '待发货' },
      { value: 'shipped', label: '已发货' },
      { value: 'completed', label: '已完成' },
      { value: 'cancelled', label: '已取消' }
    ]
    
    // 分页
    const currentPage = ref(1)
    const pageSize = ref(10)
    
    // 订单数据
    const orderList = ref([
      {
        id: 1,
        orderNo: 'DD2023040100001',
        createTime: '2023-04-01 10:23:45',
        productName: '商务定制西装套装',
        amount: 2580.00,
        status: 'completed',
        paymentMethod: '微信支付',
        receiver: '张三',
        phone: '13800138000',
        address: '北京市朝阳区某某街道某某小区1号楼1单元101',
        remarks: '请尽快发货，谢谢',
        items: [
          {
            itemName: '高级商务西装上衣',
            specs: '藏青色 L码',
            price: 1580.00,
            quantity: 1,
            subtotal: 1580.00
          },
          {
            itemName: '高级商务西装裤',
            specs: '藏青色 32码',
            price: 1000.00,
            quantity: 1,
            subtotal: 1000.00
          }
        ],
        progress: [
          { time: '2023-04-05 15:30:22', content: '订单已完成' },
          { time: '2023-04-03 09:12:35', content: '订单已签收' },
          { time: '2023-04-02 18:45:10', content: '订单已发货' },
          { time: '2023-04-02 10:30:00', content: '订单处理中' },
          { time: '2023-04-01 10:24:30', content: '订单支付成功' },
          { time: '2023-04-01 10:23:45', content: '订单已提交' }
        ]
      },
      {
        id: 2,
        orderNo: 'DD2023040200001',
        createTime: '2023-04-02 14:30:22',
        productName: '休闲定制外套',
        amount: 1280.00,
        status: 'shipped',
        paymentMethod: '支付宝',
        receiver: '李四',
        phone: '13900139000',
        address: '上海市浦东新区某某路某某号',
        remarks: '',
        items: [
          {
            itemName: '休闲定制外套',
            specs: '灰色 M码',
            price: 1280.00,
            quantity: 1,
            subtotal: 1280.00
          }
        ],
        progress: [
          { time: '2023-04-04 09:30:00', content: '订单已发货' },
          { time: '2023-04-03 14:20:15', content: '订单处理中' },
          { time: '2023-04-02 14:31:10', content: '订单支付成功' },
          { time: '2023-04-02 14:30:22', content: '订单已提交' }
        ]
      },
      {
        id: 3,
        orderNo: 'DD2023040300001',
        createTime: '2023-04-03 09:15:30',
        productName: '商务衬衫定制',
        amount: 680.00,
        status: 'pending_payment',
        paymentMethod: '',
        receiver: '王五',
        phone: '13700137000',
        address: '广州市天河区某某路某某号',
        remarks: '请选择优质面料',
        items: [
          {
            itemName: '商务衬衫定制',
            specs: '白色 41码',
            price: 680.00,
            quantity: 1,
            subtotal: 680.00
          }
        ],
        progress: [
          { time: '2023-04-03 09:15:30', content: '订单已提交' }
        ]
      }
    ])
    
    // 筛选后的数据
    const filteredOrders = computed(() => {
      let result = orderList.value
      
      if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase()
        result = result.filter(item => 
          item.orderNo.toLowerCase().includes(query) ||
          item.productName.toLowerCase().includes(query)
        )
      }
      
      if (statusFilter.value) {
        result = result.filter(item => item.status === statusFilter.value)
      }
      
      if (dateRange.value && dateRange.value.length === 2) {
        const startDate = new Date(dateRange.value[0])
        const endDate = new Date(dateRange.value[1])
        
        result = result.filter(item => {
          const orderDate = new Date(item.createTime)
          return orderDate >= startDate && orderDate <= endDate
        })
      }
      
      // 分页处理
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      return result.slice(start, end)
    })
    
    // 总订单数（单独计算，避免在计算属性中产生副作用）
    const totalFilteredOrders = computed(() => {
      let result = orderList.value
      
      if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase()
        result = result.filter(item => 
          item.orderNo.toLowerCase().includes(query) ||
          item.productName.toLowerCase().includes(query)
        )
      }
      
      if (statusFilter.value) {
        result = result.filter(item => item.status === statusFilter.value)
      }
      
      if (dateRange.value && dateRange.value.length === 2) {
        const startDate = new Date(dateRange.value[0])
        const endDate = new Date(dateRange.value[1])
        
        result = result.filter(item => {
          const orderDate = new Date(item.createTime)
          return orderDate >= startDate && orderDate <= endDate
        })
      }
      
      return result.length
    })
    
    // 处理筛选
    const handleFilter = () => {
      currentPage.value = 1
    }
    
    // 分页处理
    const handleSizeChange = (size) => {
      pageSize.value = size
      currentPage.value = 1
    }
    
    const handleCurrentChange = (page) => {
      currentPage.value = page
    }
    
    // 获取状态类型和文本
    const getStatusType = (status) => {
      const statusMap = {
        'pending_payment': 'warning',
        'processing': 'info',
        'pending_shipment': 'info',
        'shipped': 'primary',
        'completed': 'success',
        'cancelled': 'danger'
      }
      return statusMap[status] || 'info'
    }
    
    const getStatusText = (status) => {
      const statusMap = {
        'pending_payment': '待支付',
        'processing': '处理中',
        'pending_shipment': '待发货',
        'shipped': '已发货',
        'completed': '已完成',
        'cancelled': '已取消'
      }
      return statusMap[status] || '未知状态'
    }
    
    // 订单详情
    const dialogVisible = ref(false)
    const currentOrder = ref(null)
    
    const viewOrderDetail = (order) => {
      currentOrder.value = order
      dialogVisible.value = true
    }
    
    // 订单支付
    const paymentDialogVisible = ref(false)
    const selectedPaymentMethod = ref('')
    
    const payOrder = (order) => {
      currentOrder.value = order
      paymentDialogVisible.value = true
    }
    
    const confirmPayment = () => {
      if (!selectedPaymentMethod.value) {
        ElMessage.warning('请选择支付方式')
        return
      }
      
      // 简化支付处理，直接显示成功
      ElMessage.success('支付成功')
      paymentDialogVisible.value = false
      
      // 更新订单状态
      if (currentOrder.value) {
        const order = orderList.value.find(o => o.id === currentOrder.value.id)
        if (order) {
          order.status = 'processing'
          order.paymentMethod = selectedPaymentMethod.value === 'alipay' ? '支付宝' : 
                                selectedPaymentMethod.value === 'wechat' ? '微信支付' : '银行卡'
          
          // 添加支付记录
          const now = new Date()
          const payTime = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`
          
          if (!order.progress) {
            order.progress = []
          }
          
          order.progress.unshift({
            time: payTime,
            content: '订单支付成功'
          })
        }
      }
    }
    
    // 打印订单
    const printOrder = () => {
      window.print()
    }
    
    // 查看物流
    const trackOrder = (order) => {
      ElMessageBox.alert('物流单号: SF1234567890<br>当前状态: 运输中<br>预计送达时间: 2023-04-10', '物流信息', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确定'
      })
    }
    
    // 初始化
    onMounted(() => {
      // 可以在这里调用API获取订单数据
      loading.value = true
      setTimeout(() => {
        loading.value = false
      }, 1000)
    })
    
    return {
      loading,
      searchQuery,
      statusFilter,
      dateRange,
      statusOptions,
      currentPage,
      pageSize,
      totalFilteredOrders,
      orderList,
      filteredOrders,
      handleFilter,
      handleSizeChange,
      handleCurrentChange,
      getStatusType,
      getStatusText,
      dialogVisible,
      currentOrder,
      viewOrderDetail,
      paymentDialogVisible,
      selectedPaymentMethod,
      payOrder,
      confirmPayment,
      printOrder,
      trackOrder
    }
  }
}
</script>

<style scoped>
.order-info-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 500;
}

.page-header p {
  margin: 0 0 20px 0;
  color: #666;
  font-size: 14px;
}

.filter-container {
  display: flex;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 16px;
}

.filter-item {
  width: 220px;
}

.date-filter {
  width: 380px;
}

.amount {
  color: #f56c6c;
  font-weight: 500;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 订单详情 */
.order-detail {
  padding: 10px;
}

.order-items,
.order-progress,
.remarks {
  margin-top: 30px;
}

.order-items h3,
.order-progress h3,
.remarks h3 {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
  color: #333;
}

.remarks p {
  padding: 10px 15px;
  background-color: #f8f8f8;
  border-radius: 4px;
  color: #666;
}

.dialog-footer {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 支付对话框 */
.payment-dialog {
  padding: 10px;
}

.payment-info {
  text-align: center;
  margin-bottom: 20px;
}

.payment-title {
  font-size: 16px;
  color: #333;
  margin-bottom: 10px;
}

.payment-amount {
  font-size: 18px;
  font-weight: 500;
}

.payment-method {
  margin-bottom: 20px;
}

.method-title {
  margin-bottom: 10px;
  color: #333;
}

.payment-tip {
  margin-bottom: 20px;
}

@media print {
  .filter-container,
  .pagination-container,
  .dialog-footer,
  .el-table__expand-icon {
    display: none;
  }
}
</style> 